//
//  LMUniversalTool.swift
//  LMDevelopmentTool
//
//  Created by LaiMing on 2021/12/2.
//

import Foundation
import UIKit
import AVFoundation


public class LMUniversalTool: NSObject {

    //MARK: - 视图

    /// 获取当前window
    /// - Returns: 窗口
    public static func getCurrentWindow() -> UIWindow {

        if let window:UIWindow = (UIApplication.shared.delegate?.window)! {

            return window

        }else{

            if #available(iOS 13.0, *) {

                let array:Set = UIApplication.shared.connectedScenes

                let windowScene:UIWindowScene = array.first as! UIWindowScene

                //如果是普通App开发，可以使用

    //            SceneDelegate * delegate = (SceneDelegate *)windowScene.delegate;

    //            UIWindow * mainWindow = delegate.window;

                if let mainWindow:UIWindow = windowScene.value(forKeyPath:"delegate.window") as? UIWindow {

                    return mainWindow

                }else{

                    return UIApplication.shared.windows.first!
                }

            }else{

                return UIApplication.shared.keyWindow!

            }

        }

    }

    /// 获取当前显示的控制器
    /// - Returns: <#description#>
    public static func getCurrentController() -> UIViewController? {
        
        var window = UIApplication.shared.keyWindow
          //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
            
            let windows = UIApplication.shared.windows
            
            for  windowTemp in windows{
                
                if windowTemp.windowLevel == UIWindow.Level.normal{
                    
                window = windowTemp
                break
            }
          }
        }
        let vc = window?.rootViewController
        return getTopVC(withCurrentVC: vc)

    }
    
    private static func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
        
        if VC == nil {
            print("🌶： 找不到顶层控制器")
            return nil
        }
        if let presentVC = VC?.presentedViewController {
            //modal出来的 控制器
            return getTopVC(withCurrentVC: presentVC)
        }else if let tabVC = VC as? UITabBarController {
            // tabBar 的跟控制器
            if let selectVC = tabVC.selectedViewController {
                return getTopVC(withCurrentVC: selectVC)
            }
            return nil
        } else if let naiVC = VC as? UINavigationController {
            // 控制器是 nav
            return getTopVC(withCurrentVC:naiVC.visibleViewController)
        } else {
            // 返回顶控制器
            return VC
        }
    }
    
    
    /// 淡入淡出更换rootViewController
    /// - Parameter rootVC: 根控制器
    public static func restoreRootController(rootVC:UIViewController) {
        
        let window:UIWindow = getCurrentWindow()
        
        rootVC.modalTransitionStyle = .crossDissolve
        
        UIView.transition(with: window, duration: 0.5, options: .transitionCrossDissolve, animations: {
            
            let oldState = UIView.areAnimationsEnabled
            
            UIView.setAnimationsEnabled(false)
            
            window.rootViewController = rootVC
            
            UIView.setAnimationsEnabled(oldState)
            
        }) { (completion:Bool) in
            
        }
        
    }





    //MARK: - 系统信息

    /// 获取当前Version版本号
    /// - Returns: <#description#>
    public static func getAppMainVersion() -> String {
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
        return currentVersion as! String
    }

    /// 获取当前BundleID
    /// - Returns: <#description#>
    public static func getAppBundleID() -> String {
        
        if let bundleID = Bundle.main.bundleIdentifier {
            
            return bundleID
        }

        return ""
    }

    /// 获取当前设备是否iPhoneX或以上
    /// - Returns: NO= 普通iPhone  YES=iPhoneX或以上
    public static func getCurrentDeviceIsIPhoneXOrNewer() -> Bool {
        
        var iPhoneX:Bool = false

        if UIDevice.current.userInterfaceIdiom == .phone {

            if #available(iOS 11.0, *) {

                let mainWindow : UIWindow = getCurrentWindow()
     
                if mainWindow.safeAreaInsets.bottom > 0.0 {
                    
                    iPhoneX = true
                }

            }
        }
        
        return iPhoneX
    }


    /// 是否插入耳机
    /// - Returns: 是/否
    public static func getIsInsertHeadphones() -> Bool {
        
        let audioSession = AVAudioSession.sharedInstance()
        let currentRoute = audioSession.currentRoute
        
        for output in currentRoute.outputs {
            
            if output.portType == AVAudioSession.Port.headphones {
                
                return true
            }
        }
        return false
    }



    //MARK: - 系统活动周期

    /// App正在后台
    /// - Returns: <#description#>
    public static func getAppIsInBackground() -> Bool {
        
        let state =  UIApplication.shared.applicationState
        
        if state == .background {
            
            return true
            
        }else {
            
            return false
        }
    }

    /// App正在前台
    /// - Returns: <#description#>
    public static func getAppIsInForeground() -> Bool {
        
        let state =  UIApplication.shared.applicationState
        
        if state == .active {
            
            return true
            
        }else {
            
            return false
        }
    }




    //MARK: - 转换

    /// JSONString转换为字典
    ///
    /// - Parameter jsonString: jsonString description
    /// - Returns: 字典
    public static func getDictionaryFromJSONString(jsonString:String) -> Dictionary<String,Any> {
        
        guard jsonString.isEmpty == false else {
            
            return Dictionary()
        }
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! Dictionary<String,Any>
        }
        return Dictionary()
        
    }


    /// 字典转换为JSONString
    /// - Parameter dictionary: 字典参数
    /// - Returns: JSONString
    public static func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        
        if (!JSONSerialization.isValidJSONObject(dictionary)) {

            NSLog("无法解析出JSONString")
            
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        
        return JSONString! as String

    }




    //MARK: - 图片处理

    /// 获取 高斯模糊 滤镜后的图片（默认模糊值1, 此值可以大于1）
    /// - Parameter blurValue: 模糊值（越大越模糊）
    /// - Returns: UIImage图片
    public static func getGaussianBlurImage(originalImage:UIImage , blurValue:Float = 1.0) -> UIImage {
        
        let context:CIContext = CIContext.init(options: nil)
        
        let inputImage = CIImage (image: originalImage)
        //使用高斯模糊滤镜
        let filter  =  CIFilter (name:  "CIGaussianBlur" )!
        filter.setValue(inputImage, forKey:kCIInputImageKey)
        //设置模糊半径值
        filter.setValue(blurValue, forKey:kCIInputRadiusKey)
        let outputCIImage =  filter.outputImage!
        let rect = CGRect.init(x: 0,
                               y: 0,
                               width: originalImage.size.width,
                               height: originalImage.size.height)
        let cgImage = context.createCGImage(outputCIImage, from: rect)
        
        return UIImage.init(cgImage: cgImage!)
    }





    //MARK: - 文字处理

    /// 获取文字宽度
    /// - Parameters:
    ///   - labelStr: 文字
    ///   - font: 字体
    ///   - height: 高度
    /// - Returns: 返回宽度
    public static func getTextStringWidth(labelStr:String, font:UIFont , height:CGFloat) -> CGFloat {

        let statusLabelText: NSString = labelStr as NSString

        let size = CGSize.init(width: 900, height: height)

        let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)

        let strSize = statusLabelText.boundingRect(with: size,
                                                   options: .usesLineFragmentOrigin,
                                                   attributes: dic as! [NSAttributedString.Key : Any],
                                                   context: nil).size

        return strSize.width
    }


    /// 判断是否是数字
    ///
    /// - Parameter string: <#string description#>
    /// - Returns: <#return value description#>
    public static func getTextIPurnInt(string: String) -> Bool {
        
        let scan: Scanner = Scanner(string: string)
        
        var val:Int = 0
        
        return scan.scanInt(&val) && scan.isAtEnd
        
    }


    //MARK: - 时间处理

    /// 获取当前时间
    /// - Returns: 时间date
    public static func getCurrentTime() -> Date
    {
        //获取当前时间0秒后的时间
        return Date.init(timeIntervalSinceNow: 0)
        
    }


    /// 获取当前时间戳(10位，精确到秒)
    /// - Returns: 字符串
    public static func getCurrentTimeStamp() -> String
    {
        let time:TimeInterval = getCurrentTime().timeIntervalSince1970
        // *1000 是精确到毫秒，不乘就是精确到秒
        
        return String(time) as String
    }




    //MARK: - 权限处理

    /// 打开app权限
    public static func goOpenSettingAppAuth()
    {
        
        let settingUrl = URL.init(string: UIApplication.openSettingsURLString)!
        
        
        if #available(iOS 10.0, *) {
            
            UIApplication.shared.open(settingUrl, options:[:]) { (finish:Bool) in
                
            }
            
        } else {
            
            UIApplication.shared.openURL(settingUrl)
        }
        
    }



}
